// const app = getApp()
import Host from '@/utils/host'
import Session from '@/utils/session';
const host = Host.host

const request = (url, options) => {
	// 请求之前提示加载中
	wx.showLoading({
		title: '加载中...'
	})
	const token = Session.get('x-token')
	return new Promise((resolve, reject) => {
		wx.request({
			// url: `${app.globalData.baseURL}${url}`,
			url: host + url,
			method: options.method,
			data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
			header: {
				'Content-Type': 'application/json; charset=UTF-8',
				'token': token // 看自己是否需要
			},
			// success: resolve,
			fail: reject,
			success(request) {
				console.log(request)
				const token = Session.get('x-token') || ""
				if (token!=="" && request.data.resultCode === 403) {
					console.log(1);
					Session.clear('x-token')
					wx.reLaunch({
						url: '/pages/home'
					})
				} else {
					resolve(request)
				}
			},
			// fail(error) {
			//   reject(error.data)
			// }
			complete() {
				wx.hideLoading()
			}
		})
	})
}

const get = (url, options = {}) => {
	return request(url, {
		method: 'GET',
		data: options
	})
}

const post = (url, options) => {
	return request(url, {
		method: 'POST',
		data: options
	})
}

const put = (url, options) => {
	return request(url, {
		method: 'PUT',
		data: options
	})
}

// 不能声明DELETE（关键字）
const remove = (url, options) => {
	return request(url, {
		method: 'DELETE',
		data: options
	})
}

module.exports = {
	get,
	post,
	put,
	remove
}